package oop.ex3.search;
import java.util.Date;
import java.util.Iterator;

import oop.ex3.search.DepthFirstSearch;

public class MyDepthFirstSearch <B extends SearchBoardNode<M>,M extends SearchMove > implements DepthFirstSearch  {


	@Override
	public SearchBoardNode search(SearchBoardNode startBoard, int maxDepth,
			long timeOut) {
		Date date= new Date();
		long originalTime= date.getTime();
		return search(startBoard,startBoard.getCopy(),maxDepth,timeOut, originalTime);

	}
	private SearchBoardNode<M> search(SearchBoardNode<M> startBoard,SearchBoardNode<M> bestBoard, int maxDepth,
			long timeOut, long originalTime) {
		Date date= new Date();

		if (date.getTime()-originalTime< timeOut){
			if (maxDepth>0){
				Iterator<M> iter= startBoard.getMovesIterator();
				SearchBoardNode<M> temp;
				while (iter.hasNext()){
					M move= iter.next();
					startBoard.doMove(move);
					temp=search(startBoard,bestBoard.getCopy(), maxDepth-1, timeOut,originalTime);
					bestBoard=bestBoard.getQuality()>temp.getQuality()?bestBoard:temp.getCopy();
					startBoard.undoMove(move);
				}
				return bestBoard;
			}
			return startBoard.getCopy();
		}
		return bestBoard;


	}


}
